package stats;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class ExecutorConcurrentHashMapStatsService implements IStatsService
{
	private ExecutorService							executor	= Executors.newSingleThreadExecutor();
	private ConcurrentHashMap<String, AtomicLong>	stats;

	public ExecutorConcurrentHashMapStatsService ()
	{
		init();
	}

	private void init ( )
	{
		stats = new ConcurrentHashMap<String, AtomicLong>(5000, 1, 50);
	}

	public void notify ( final String key )
	{
		Runnable r = new Runnable()
		{
			public void run ( )
			{
				AtomicLong value = stats.get(key);
				if (value == null)
				{
					value = stats.putIfAbsent(key, new AtomicLong(1));
				}
				if (value != null)
				{
					value.incrementAndGet();
				}
			}
		};
		executor.execute(r);
	}

	public Map<String, Number> getStats ( )
	{
		Map<String, AtomicLong> statsRef = stats;
		init();
		return new HashMap<String, Number>(statsRef);
	}

	public void stop ( )
	{
		executor.shutdown();
		while (!executor.isTerminated());
	}
}
